package data

import (
	"fmt"
	"manage/app/class/internal/biz"
	"strings"
	"time"

	"github.com/Fromsko/gouitls/auth"
	"github.com/Fromsko/gouitls/logs"
	"github.com/go-kratos/kratos/v2/log"
	"gorm.io/gorm"
)

type classRepo struct {
	data *Data
	log  *log.Helper
}

func NewClassRepo(data *Data, logger log.Logger) biz.ClassRepo {
	c := &classRepo{
		data: data,
		log:  log.NewHelper(logger),
	}
	c.setup()
	return c
}

func (u classRepo) setup() {
	var echo = logs.InitLogger()

	db := u.data.Mysql
	if db.Migrator().HasTable(biz.Class{}) {
		echo.Warn("班级表已存在, 跳过创建。")
		return
	}

	if err := db.AutoMigrate(biz.Class{}); err != nil {
		echo.Errorf("创建表失败：%v", err)
	} else {
		echo.Info("班级表创建完成")
	}
}

func (repo *classRepo) CreateClass(request *biz.CreateClassRequest) (*biz.CreateClassResponse, error) {
	t := time.Now()
	existingClass := &biz.Class{}
	result := repo.data.Mysql.Where("class_name = ?", request.ClassName).First(existingClass)

	if result.Error == nil {
		return nil, fmt.Errorf("班级%s已经存在", request.ClassName)
	} else if result.Error != gorm.ErrRecordNotFound {
		return nil, result.Error
	}

	newClass := &biz.Class{
		ClassName: request.ClassName,
		TeacherID: request.TeacherID,
		ClassId:   strings.Split(auth.GenUUID(request.ClassName), "-")[4],
		CreatedAt: t,
		UpdatedAt: t,
	}

	if result = repo.data.Mysql.Create(newClass); result.Error != nil {
		return nil, result.Error
	}

	return &biz.CreateClassResponse{
		Message: "班级创建成功",
		ClassID: newClass.ClassId,
	}, nil
}

func (repo *classRepo) DeleteClass(classID string) error {
	result := repo.data.Mysql.Where("class_id = ?", classID).Delete(&biz.Class{})
	if result.Error != nil {
		return fmt.Errorf("删除失败:%s-%v", classID, result.Error)
	}
	if result.RowsAffected == 0 {
		return fmt.Errorf("班级不存在")
	}
	return nil
}

func (repo *classRepo) UpdateClass(request *biz.CreateClassRequest, classID string) error {
	tmp := &biz.Class{
		UpdatedAt: time.Now(),
		ClassName: request.ClassName,
		TeacherID: request.TeacherID,
	}

	result := repo.data.Mysql.Model(tmp).Where("class_id = ?", classID).Updates(tmp)
	if result.Error != nil {
		return fmt.Errorf("更新班级失败-%v", result.Error)
	}
	if result.RowsAffected == 0 {
		return fmt.Errorf("班级不存在")
	}
	return nil
}

func (repo *classRepo) GetClassInfo(classID string) (*biz.GetClassResponse, error) {
	var classInfo biz.Class
	result := repo.data.Mysql.Where("class_id = ?", classID).Find(&classInfo)

	if result.Error != nil {
		return nil, result.Error
	}

	if result.RowsAffected == 0 {
		return nil, fmt.Errorf("班级不存在")
	}

	return &biz.GetClassResponse{
		ClassID:   classInfo.ClassId,
		ClassName: classInfo.ClassName,
		TeacherID: classInfo.TeacherID,
	}, nil
}
